<?php

namespace common\observer;

use support\SingletonTrait;
use common\model\TaskModel;
use common\model\TaskMemberModel;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 任务完成或者开始,同步到任务成员状态
 */
class TaskStatusSyncToTaskMember implements SplObserver
{
    use SingletonTrait;

    /**
     * @inheritDoc
     */
    function update(SplSubject $subject): void
    {
        $updateData = $subject->getSplUpdateData();
        if (!isset($updateData['task_status'])) {
            return;
        }
        $task = $subject->getSubjectData();
        if ($task['step_type'] != TaskModel::STEP_TYPE_STEP) {
            return;
        }

        $taskMemberList = model(TaskMemberModel::class)->where(['task_id' => $task['id']])->select();
        $taskMemberIdList = array_column($taskMemberList, 'id');
        if (empty($taskMemberIdList)) {
            return;
        }

        try {
            foreach ($taskMemberList as $taskMember) {
                model(TaskMemberModel::class)->modifyItem(['id' => $taskMember['id'], 'status' => $updateData['task_status']]);
            }
        } catch (\Throwable $e) {
            trace(format_exception_info($e), 'ERR');
        }
    }
}
